<?php
namespace app\controller;

use app\BaseController;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use OSS\OssClient;
use OSS\Core\OssException;

class Upload extends BaseController 
{
    public function getSTSToken()
    {
        $token = request()->header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $user = \think\facade\Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        $accessKeyId = env("ALI_OSS_ACCESS_KEY_ID");
        $accessKeySecret = env("ALI_OSS_ACCESS_KEY_SECRET");
        $roleArn = env("ALI_OSS_ACCESS_ROLE_ARN");
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
    ->regionId('cn-hangzhou')
    ->asDefaultClient();
    try {
        // 创建STS请求。
        $result = AlibabaCloud::rpc()
                ->scheme('https')
                ->product('Sts')
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => env('ALI_OSS_REGION', 'cn-hangzhou'),
                        'RoleArn' => $roleArn,
                        'RoleSessionName' => "sessiontest",
                        'DurationSeconds' => 3600,
                    ],
                ])
                ->request();
    
        // 获取响应中的凭证信息。
        $credentials = $result['Credentials'];
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'accessKeyId' => $credentials['AccessKeyId'],
                'accessKeySecret' => $credentials['AccessKeySecret'],
                'securityToken' => $credentials['SecurityToken'],
                'expiration' => $credentials['Expiration'],
                'region' => env('ALI_OSS_REGION', 'cn-hangzhou'),
                'bucket' => env('ALI_OSS_BUCKET', 'cn-hangzhou'),
                'endpoint' => env('ALI_OSS_END_POINT')
            ]
        ]);
    } catch (ClientException $e) {
        // 处理客户端异常。
        echo $e->getErrorMessage() . PHP_EOL;
    } catch (ServerException $e) {
        // 处理服务端异常。
        echo $e->getErrorMessage() . PHP_EOL;
    }
    }
}